var params = app.getRequestParams();
var _type = [{value:1,text:'预收冲应收'},
    {value:2,text:'预付冲应付'},
    {value:3,text:'应收冲应付'},
    {value:4,text:'应收转应收'},
    {value:5,text:'应付转应付'}];
var _typeObj = {};
for( var i=0 ; i<_type.length ; i++ ){
    _typeObj[_type[i].value] = _type[i].text;
}
$(function(){
    initPage();
});

function initPage() {
    $('#fixtable_zu').fixgrid({
        noscroll:true,
        width:950,
        columns:[
            [
                {field:'serialnumber',title:'',width:30},
                {field:'o',title:'操作',width:60,formatter:function () {
                        return gridOpt('#fixtable_zu');
                    }},
            ],[
                {field:'orderType',title:'业务类别',width:120},
                {field:'date',title:'单据日期',width:120,n:'date'},
                {field:'code',title:'单据编号',width:120},
                {field:'orderMoney',title:'单据金额',width:120,n:'money'},
                {field:'verificateMoney',title:'已核销金额',width:120,n:'money'},
                {field:'xxx',title:'未核销金额',width:120,n:'money'},
                {field:'currVerificateMoney',title:'<span class="red">*</span>核销金额',width:100,n:'money',editor:'decimal'}
            ]
        ]
    });

    $('#fixtable_ge').fixgrid({
        noscroll:true,
        width:950,
        columns:[
            [
                {field:'serialnumber',title:'',width:30},
                {field:'o',title:'操作',width:60,formatter:function () {
                        return gridOpt('#fixtable_ge');
                    }},
            ],[
                {field:'orderType',title:'业务类别',width:120},
                {field:'date',title:'单据日期',width:120,n:'date'},
                {field:'code',title:'单据编号',width:120},
                {field:'orderMoney',title:'单据金额',width:120,n:'money'},
                {field:'verificateMoney',title:'已核销金额',width:120,n:'money'},
                {field:'xxx',title:'未核销金额',width:120,n:'money'},
                {field:'currVerificateMoney',title:'<span class="red">*</span>核销金额',width:100,n:'money',editor:'decimal'}
            ]
        ]
    });

    createChoseOrderBtn('_zu','选择预收单据');
    createChoseOrderBtn('_ge','选择应收单据');

    if(params.status==2){
        editable = false;
    }
    
    initButtons({service:'verificate',htmlName:'verification',orderText:'核销单',codePrefix:'HX',orderType:0,gridId:'#fixtable_zu'});

    $('textarea[name="order.remarks"]').width($('#fixtable_zu').width()-14);

    $('#verificateType').combobox({
        width:180,noDefault:true,
        data:_type,
        name:'order.type',
        change:verificateTypeChange
    });

    $('#verificateType').combobox('setValue',1,'预收冲应收');
    $('#bussCustomerId_txt').html('核销客户');
    $('.table td[type="vendor"]').hide();

    $('#bussCustomerId').search({
        width:180,
        name:'order.relationId1',
        click:function () {
            if( '转出供应商' == $('#bussCustomerId_txt').html() ){
                searchClickVendor('bussCustomerId');
            }else{
                searchClickCustomer('bussCustomerId');
            }
        }
    });

    $('#vendorId').search({
        width:180,
        name:'order.relationId2',
        click:function () {
            if( '转出客户' == $('#bussCustomerId_txt').html() ){
                searchClickCustomer('vendorId');
            }else{
                searchClickVendor('vendorId');
            }
        }
    });

    laydate.render({
        elem: '#order_date',value:app.getServerDate()
    });

    // 必须放在最后  所有代码要写在之前
    if(params.id){
        app.request({
            url:'verificate/getOrder',
            data:{id:params.id},
            success:function (resp) {
                initEdit(resp.data);
            }
        });
    }else{
        $('#order_title').html('新增核销单');
        createRow('#fixtable_zu');createRow('#fixtable_zu');
        createRow('#fixtable_ge');createRow('#fixtable_ge');createRow('#fixtable_ge');
    }
}

function verificateTypeChange(row,order) {
    $('.table td[type="vendor"]').hide();
    $('.table td[type="customer"]').hide();
    $('#bussCustomerId').search('setValue','','');
    $('#vendorId').search('setValue','','');
    if( row.value == 1 ){
        $('#bussCustomerId_txt').html('核销客户');
        $('.table td[type="customer"]').show();
        $('#choseOrder_zu span').html('选择预收单据');
        $('#choseOrder_ge span').html('选择应收单据');
        $('#fixtable_ge').show();$('#choseOrderDiv_ge').show();

        $('#bussCustomerId').search('setValue',order.relationId1,order.relationName1);
    }else if( row.value == 2 ){
        $('#vendorId_txt').html('核销供应商');
        $('.table td[type="vendor"]').show();
        $('#choseOrder_zu span').html('选择预付单据');
        $('#choseOrder_ge span').html('选择应付单据');
        $('#fixtable_ge').show();$('#choseOrderDiv_ge').show();

        $('#vendorId').search('setValue',order.relationId2,order.relationName2);
    }else if( row.value == 3 ){
        $('.table td[type="customer"]').show();
        $('.table td[type="vendor"]').show();
        $('#bussCustomerId_txt').html('客户');
        $('#vendorId_txt').html('供应商');
        $('#choseOrder_zu span').html('选择应收单据');
        $('#choseOrder_ge span').html('选择应付单据');
        $('#fixtable_ge').show();$('#choseOrderDiv_ge').show();
        $('#bussCustomerId').search('setValue',order.relationId1,order.relationName1);
        $('#vendorId').search('setValue',order.relationId2,order.relationName2);
    }else if( row.value == 4 ){
        $('.table td[type="customer"]').show();
        $('.table td[type="vendor"]').show();
        $('#bussCustomerId_txt').html('转出客户');
        $('#vendorId_txt').html('转入客户');
        $('#choseOrder_zu span').html('选择应收单据');
        $('#choseOrder_ge span').html('选择应收单据');
        $('#fixtable_ge').hide();$('#choseOrderDiv_ge').hide();
        $('#bussCustomerId').search('setValue',order.relationId1,order.relationName1);
        $('#vendorId').search('setValue',order.relationId2,order.relationName2);
    }else if( row.value == 5 ){
        $('.table td[type="customer"]').show();
        $('.table td[type="vendor"]').show();
        $('#bussCustomerId_txt').html('转出供应商');
        $('#vendorId_txt').html('转入供应商');
        $('#choseOrder_zu span').html('选择应付单据');
        $('#choseOrder_ge span').html('选择应付单据');
        $('#fixtable_ge').hide();$('#choseOrderDiv_ge').hide();
        $('#bussCustomerId').search('setValue',order.relationId1,order.relationName1);
        $('#vendorId').search('setValue',order.relationId2,order.relationName2);
    }
}

function verifiorderList(btnType) {
    var type = $('input[name="order.type"]').val();
    var relation1 = $('input[name="order.relationId1"]').val();
    var relation2 = $('input[name="order.relationId2"]').val();
    var data = {type:type,btnType:btnType};
    if( type == 1 ){
        if( btnType == '_zu' ){
            if( !relation1 ){
                app.msg(layer,'请先选择客户');
                return;
            }
            data.pageType = 1;
            data.relationId = relation1;
            data.receiptType = 1;
        }else{
            if( !relation1 ){
                app.msg(layer,'请先选择客户');
                return;
            }
            data.pageType = 2;
            data.relationId = relation1;
            data.orderType = 22;
        }
    }else if( type == 2 ){
        if( btnType == '_zu' ){
            if( !relation2 ){
                app.msg(layer,'请先选择供应商');
                return;
            }
            data.pageType = 1;
            data.relationId = relation2;
            data.receiptType = 2;
        }else{
            if( !relation2 ){
                app.msg(layer,'请先选择供应商');
                return;
            }
            data.pageType = 2;
            data.relationId = relation2;
            data.orderType = 3;
        }
    }else if( type == 3 ){
        if( btnType == '_zu' ){
            if( !relation1 ){
                app.msg(layer,'请先选择客户');
                return;
            }
            data.pageType = 2;
            data.relationId = relation1;
            data.orderType = 22;
        }else{
            if( !relation2 ){
                app.msg(layer,'请先选择供应商');
                return;
            }
            data.pageType = 2;
            data.relationId = relation2;
            data.orderType = 3;
        }
    }else if( type == 4 ){
        if( btnType == '_zu' ){
            if( !relation1 || !relation2 ){
                app.msg(layer,'请先选择客户');
                return;
            }
            data.pageType = 2;
            data.relationId = relation1;
            data.orderType = 22;
        }
    }else if( type == 5 ){
        if( btnType == '_zu' ){
            if( !relation1 || !relation2 ){
                app.msg(layer,'请先选择供应商');
                return;
            }
            data.pageType = 2;
            data.relationId = relation1;
            data.orderType = 3;
        }
    }

    var url = '../../finance/verifiorder_list.html?index=-1&queryId=-1';
    for( var n in data ){
        url += '&'+ n + '='+ data[n];
    }

    app.window(layer,{
        title:'源单选择',
        area: ['800px', '600px'],
        content: url
    });
}

function searchClickVendor(queryId) {
    app.window(layer,{
        title:'供应商选择',
        btn:[],
        area: ['860px', '600px'],
        content: '../../common/vendor_list.html?index=-1&queryId='+queryId
    });
}

function searchClickCustomer(queryId) {
    app.window(layer,{
        title:'客户选择',
        btn:[],
        area: ['860px', '600px'],
        content: '../../common/customer_list.html?index=-1&queryId='+queryId
    });
}

function createChoseOrderBtn(type,btnTxt) {
    var choseOrderBtn = $('<button class="button" id="choseOrder'+type+'"><span>'+btnTxt+'</span></button>');
    choseOrderBtn.css({"margin-left":($('#fixtable'+type).width()-100)+"px"});
    choseOrderBtn.click(function () {
        verifiorderList(type);
    });
    $('#choseOrderDiv'+type).append(choseOrderBtn);
    if( type == '_zu' ) $('#choseOrderDiv'+type).css({"padding-top":"0px"});
}

//编辑初始化
function initEdit(data){
    var order = data.order;
    var details = data.details;

    init_edit_buttons(order,'#fixtable_zu');

    $('#order_title').html('编辑核销单【HX'+order.code+'】');

    $('#order_date').val(app.time2str(parseInt(order.date)));
    $('textarea[name="order.remarks"]').val(order.remarks);
    $('#verificateType').combobox('setValue',order.type,_typeObj[order.type]);
    verificateTypeChange({value:order.type},order);


    $('input[name="order.relationId_text"]').val(order.relationName);
    $('input[name="order.relationId"]').val(order.relationId);

    $('#employeeId').combobox('setValue',order.receiptUserId,order.userName);

    for (var i=0 ; i<details.length ; i++){
        var row = details[i];
        var xtype = row.type == 1 ?'_zu':'_ge';
        createRow('#fixtable'+xtype);
        var lastRowEle = $('#fixtable'+xtype+' .ctx-right .vui-table-row').last();

        row.date = row.billDate;
        row.code = row.billCode;
        row.id = row.targetId;
        if( (order.type == 1 || order.type == 2 ) && row.type == 1  ){
            row.billType = row.targetType;
        }else{
            row.orderType = row.targetType;
        }

        lastRowEle.data(row);
        lastRowEle.find('.vui-table-cell[field="orderType"]').html(billTypeFormat(row));
        lastRowEle.find('.vui-table-cell[field="date"]').html(app.time2str(row.date));
        lastRowEle.find('.vui-table-cell[field="code"]').html(codeFormat(row));
        lastRowEle.find('.vui-table-cell[field="orderMoney"]').html(app.div(row.billPrice,app.DIV));
        lastRowEle.find('.vui-table-cell[field="verificateMoney"]').html(app.div(row.verificatedMoney,app.DIV));
        lastRowEle.find('.vui-table-cell[field="xxx"]').html(app.div(app.sub(row.billPrice,row.verificatedMoney),app.DIV));
        lastRowEle.find('.vui-table-cell[field="currVerificateMoney"]').html(app.div(row.verificateMoney,app.DIV));
    }
}

function codeFormat(row) {
    if( row.orderType ){
        if( row.orderType == 22 ){
            return 'SH'+row.code;
        }else if( row.orderType == 4 ){
            return 'CT'+row.code;
        }else if( row.orderType == 23 ){
            return 'XT'+row.code;
        }else if( row.orderType == 3 ){
            return 'CG'+row.code;
        }
    }else{
        if( row.billType == 1 ){
            return 'SK'+row.code;
        }else if( row.billType == 2 ){
            return 'FK'+row.code;
        }
    }
}

function billTypeFormat(row) {
    if( row.orderType ){
        if( row.orderType == 22 ){
            return '销售单';
        }else if( row.orderType == 4 ){
            return '采购退货单';
        }else if( row.orderType == 23 ){
            return '销售退货单';
        }else if( row.orderType == 3 ){
            return '采购单';
        }
    }else{
        if( row.billType == 1 ){
            return '收款单';
        }else if( row.billType == 2 ){
            return '付款单';
        }
    }

}

//保存
var accounts = [];
function saveAction(saveType,obj){
    var orderBeforeMoney = 0;
    $.each(orderDetails,function(i,row){
        if( row.type == 1 ){
            orderBeforeMoney = app.add(orderBeforeMoney,row.verificateMoney);
        }
    });

    var orderAfterMoney = 0;
    $.each(orderDetails,function(i,row){
        if( row.type == 2 ){
            orderAfterMoney = app.add(orderAfterMoney,row.verificateMoney);
        }
    });

    var data = app.serializeForm();
    data.saveType = saveType;
    data['order.type'] = $('input[name="order.type"]').val();

    $.each(orderDetails,function(i,row){
        for ( var n in row ){
            data["details["+i+"]."+n] = row[n];
        }
        data["details["+i+"].ord"] = i;
    });

    var url = 'verificate/insert';
    if(params.id){
        data['order.id'] = params.id;
        url = 'verificate/update';
    }

    if( orderBeforeMoney != orderAfterMoney ){
        var xtype = data['order.type'];
        var txt = xtype==1?'预收、应收':xtype==2?'预付、应付':xtype==3?'应收、应付':xtype==4?'应收、应收':xtype==5?'应付、应付':'';
        layer.confirm(txt+'核销金额不一致，是否继续？', {icon: 3, title:'提示'}, function(index){
            layer.load();
            doSave(url,data,saveType,obj);
        });
        layer.closeAll('loading');
    }else{
        doSave(url,data,saveType,obj);
    }

}

//表单检查
var orderDetails = [],orderOrders = [];
function checkForm(){

    var checkOptions = [
        {type:'input',name:'order.date',verify:[{type:'required'}]}
    ];

    if(app.checkForm(checkOptions)){
        orderDetails = [];
        var xtype = $('input[name="order.type"]').val();
        if( xtype < 4 ){
            if(!getOrderDetails('fixtable_zu',1))return false;
            return getOrderDetails('fixtable_ge',2);
        }else {
            return getOrderDetails('fixtable_zu',1);
        }
    }

    return false;
}

function getOrderDetails(gridId,verType) {
    var tipFlag = true;
    var orderDetailsLen = orderDetails.length;
    $('#'+gridId+' .ctx-right .vui-table-row').each(function () {
        var detail = {};
        var row = $(this).data();

        if( row && row.id ){
            var currVerificateMoneyEle = $(this).find('.vui-table-cell[field="currVerificateMoney"]');
            var orderMoney = $(this).find('.vui-table-cell[field="orderMoney"]').html();
            var verificateMoney = $(this).find('.vui-table-cell[field="verificateMoney"]').html();
            var currVerificateMoney = currVerificateMoneyEle.html();

            detail.type = verType;
            detail.billDate = row.date;
            detail.billCode = row.code;
            detail.billPrice = app.transNumber(app.mul(orderMoney,app.DIV));
            detail.targetId = row.id;
            detail.targetType = row.orderType?row.orderType:row.billType;
            detail.verificatedMoney = app.transNumber(app.mul(verificateMoney,app.DIV));

            if( $.trim(currVerificateMoney).length == 0 ){
                layer.tips('请填写核销金额', currVerificateMoneyEle, {
                    tips: [1, '#3595CC'],
                    time: 3000
                });
                tipFlag = false;
                return;
            }
            detail.verificateMoney = app.transNumber(app.mul(currVerificateMoney,app.DIV));
            if( parseFloat(app.sub(currVerificateMoney,0)) > parseFloat(app.sub(orderMoney,verificateMoney)) ){
                layer.tips('核销金额不能大于未核销金额', currVerificateMoneyEle, {
                    tips: [1, '#3595CC'],
                    time: 3000
                });
                tipFlag = false;
                return;
            }
            orderDetails.push(detail);
        }
    });

    if(tipFlag){
        if( orderDetails.length == orderDetailsLen ){
            var xtype = $('input[name="order.type"]').val();
            var xtxt = xtype==1? '预收':xtype==2? '预付':xtype==3? '应收':xtype==4? '应收':xtype==5? '应付':'';
            app.msg(layer,'至少选择一条'+xtxt+'单据记录',2);
            return false;
        }
        return true;
    }else{
        return false;
    }
}
